package com.cjc.sport.serviceimpl;

import com.cjc.sport.entity.EnumValidation;
import com.cjc.sport.entity.Shuffling;
import com.cjc.sport.entity.Sort;
import com.cjc.sport.exception.ServiceException;
import com.cjc.sport.mapper.ShufflingMapper;
import com.cjc.sport.service.ShufflingService;
import com.cjc.sport.util.SportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 轮播图服务层实现类
 *
 * @Author: Bruse Queen
 * @Date: 2018/2/28
 */
@Service(value = "shufflingService")
public class ShufflingServiceImpl implements ShufflingService {

    /**
     * 装配轮播图mapper
     */
    @Autowired
    private ShufflingMapper shufflingMapper;
    /**
     * 引入配置文件
     */
    @Autowired
    private Environment environment;

    @Override
    public void addShuffling(Shuffling shuffling) {
        // 判断序号冲突
        if (jedgeDuplicationAdd(shuffling)) {
            throw new ServiceException("已有此序号！");
        }
        // 设置停留时间为数据库中第一条数据值
        if (null == getShuffling()) {
            shuffling.setKeepTime(EnumValidation.TWO.getNum());
        } else {
            shuffling.setKeepTime(getShuffling().getKeepTime());
        }

        // 设置uuid
        shuffling.setId(SportUtils.getUuid());
        // 去除imgurl链接
//        System.out.println(environment.getProperty("img.url"));
//        shuffling.setImgUrl(shuffling.getUrl().replace(environment.getProperty("img.url"), ""));
        // 执行新增
        int i = shufflingMapper.insertSelective(shuffling);
        if (i != 1) {
            throw new ServiceException("新增失败!");
        }
        return;
    }

    @Override
    public void updateShuffling(Shuffling shuffling) {
        // 查询数据库中此条数据
        Shuffling shufflingTemp = shufflingMapper.selectByPrimaryKey(shuffling.getId());
        if (null == shufflingTemp) {
            throw new ServiceException("轮播图ID错误！");
        }

        if (shufflingTemp.equals(shuffling)) {
//            throw new ServiceException("您未修改任何信息!");
        }

        if (judgeDuplication(shuffling)) {
            throw new ServiceException("已有此序号！");
        }

        // 设置停留时间为数据库中第一条数据值
        if (null == getShuffling()) {
            shuffling.setKeepTime(EnumValidation.TWO.getNum());
        } else {
            shuffling.setKeepTime(getShuffling().getKeepTime());
        }

        // 去除imgurl链接
//        System.out.println(environment.getProperty("img.url"));
//        shuffling.setImgUrl(shuffling.getUrl().replace(environment.getProperty("img.url"), ""));
        // 执行编辑
        int i = shufflingMapper.updateByPrimaryKeySelective(shuffling);
        if (i != 1) {
            throw new ServiceException("编辑失败!");
        }
        return;
    }

    @Override
    public void deleteShuffling(Shuffling shuffling) {
        // 执行删除
        int i = shufflingMapper.deleteByPrimaryKey(shuffling.getId());
        if (i != 1) {
            throw new ServiceException("删除失败!");
        }
        return;
    }

    @Override
    public List<Shuffling> getAllShuffling() {
        // 执行查询
        List<Shuffling> shufflings = shufflingMapper.selectAllShuffling();
        if (shufflings.isEmpty()) {
            throw new ServiceException("暂无相关数据!");
        }
        //format的格式设置
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 遍历转化更新时间和设置imgUrl
        for (Shuffling shuffling : shufflings) {
            String dateStr = dateFormat.format(shuffling.getCreateDate());
            shuffling.setUpdateDateString(dateStr);
            shuffling.setImgUrl(environment.getProperty("img.url") + shuffling.getImgUrl());
        }
//        shufflings.forEach(s -> {
//            String dateStr = dateFormat.format(s.getUpdateDate());
//            s.setUpdateDateString(dateStr);
//            s.setImgUrl(environment.getProperty("img.url") + s.getImgUrl());
//        });
        return shufflings;
    }

    @Override
    public void updateShufflingTime(Shuffling shuffling) {
        // 执行编辑
        int i = shufflingMapper.updateKeepTime(shuffling.getKeepTime());
        List<Shuffling> shufflings = shufflingMapper.selectAllShuffling();
        if (i != shufflings.size()) {
            throw new ServiceException("编辑失败!");
        }
    }

    @Override
    public void sortShuffling(List<Sort> item, int pageNum, int pageSize) {
        // 解析排序集合
        List<Shuffling> shufflings = new ArrayList<>();
        for (Sort sort : item) {
            Shuffling shuffling = new Shuffling();
            shuffling.setId(sort.getKey());
            shuffling.setShufflingNum(sort.getValue());
            shufflings.add(shuffling);
        }
        // 特别说明，如果以后需要开启分页排序，将分页打开，然后前端传入正确带分页数据即可
        // 设置分页
//        PageHelper.startPage(pageNum, pageSize);
        // 获取旧数据
        List<Shuffling> shufflingsOld = shufflingMapper.selectAllShuffling();
        if (shufflings.size() != shufflingsOld.size()) {
            throw new ServiceException("数据异常，请刷新后再试！");
        }
        // 新旧数据交替赋值
        for (int i = 0; i < shufflingsOld.size(); i++) {
            shufflings.get(i).setShufflingNum(shufflingsOld.get(i).getShufflingNum());
        }
        // 执行排序
        for (Shuffling shuffling : shufflings) {
            int i = shufflingMapper.updateByPrimaryKeySelective(shuffling);
            if (i != 1) {
                throw new ServiceException("排序过程中出错！");
            }
        }
        // 对序号进行重新排序
        List<Shuffling> shufflingsAll = shufflingMapper.selectAllShuffling();
        for (int i = 0; i != shufflingsAll.size(); i++) {
            Shuffling shufflingTemp = shufflingsAll.get(i);
            shufflingTemp.setShufflingNum(i + 1);
            int j = shufflingMapper.updateByPrimaryKeySelective(shufflingTemp);
            if (j != 1) {
                throw new ServiceException("对序号进行重新排序时出错！");
            }
        }
        return;
    }

    @Override
    public List<Shuffling> getTrueShuffling() {
        // 执行查询
        List<Shuffling> shufflings = shufflingMapper.getTrueShuffling();
        if (shufflings.isEmpty()) {
            throw new ServiceException("暂无相关数据!");
        }
        // 设置imgUrl
        for (Shuffling shuffling : shufflings) {
            shuffling.setImgUrl(environment.getProperty("img.url") + shuffling.getImgUrl());
        }
//        shufflings.forEach(s -> s.setImgUrl(environment.getProperty("img.url") + s.getImgUrl()));
        return shufflings;
    }

    /**
     * 编辑时判断是否有同序号轮播图
     *
     * @param shuffling 轮播图对象
     * @return 0 无 1 有
     */
    public boolean judgeDuplication(Shuffling shuffling) {
        List<Shuffling> shufflings = shufflingMapper.selectByShufflingNum(shuffling.getShufflingNum());
        if (!shufflings.isEmpty() && !shuffling.getId().equals(shufflings.get(0).getId())) {
            return true;
        }
        return false;
    }

    /**
     * 新增时判断是否有同序号轮播图
     *
     * @param shuffling 轮播图对象
     * @return 0 无 1 有
     */
    public boolean jedgeDuplicationAdd(Shuffling shuffling) {
        List<Shuffling> shufflings = shufflingMapper.selectByShufflingNum(shuffling.getShufflingNum());
        if (!shufflings.isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 获取一个轮播图对象
     *
     * @return Shuffling 轮播图对象
     */
    public Shuffling getShuffling() {
        return shufflingMapper.selectOne();
    }
}
